package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.UserLike;
import com.itheima.domain.mongo.Visitor;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.UserLikeCountVo;
import com.itheima.domain.vo.UserLikeVo;
import com.itheima.service.mongo.UserLikeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service //dubbo
public class UserLikeServiceImpl implements UserLikeService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    //保存喜欢
    public void save(UserLike userLike) {
        //先查询表中有无此条数据,若无则保存
        boolean exists = mongoTemplate.exists(Query.query(Criteria.where("userId").is(userLike.getUserId()).and("likeUserId").is(userLike.getLikeUserId())), UserLike.class);

        if (!exists) {
            mongoTemplate.save(userLike);
        }
    }

    @Override
    //是否相互喜欢
    public boolean isMutualLike(Long userId, Long likeUserId) {
        boolean exists1 = mongoTemplate.exists(Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId)), UserLike.class);
        boolean exists2 = mongoTemplate.exists(Query.query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId)), UserLike.class);
        return exists1 && exists2;
    }

    @Override
    //删除我的喜欢
    public void delete(Long userId, Long likeUserId) {
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId)),UserLike.class);
    }

    @Override
    public UserLikeCountVo findEveryCount(Long userId) {
        //- 相互喜欢: 查询好友列表 (  从`friend`表中根据`userId`查询我的所有好友数量  )
        long eachCount = mongoTemplate.count(Query.query(Criteria.where("userId").is(userId)), Friend.class);

        //- 喜欢: 查询你喜欢的用户 (  从`user_like`表中根据`userId`查询所有我喜欢的用户数量  )
        long loveCount = mongoTemplate.count(Query.query(Criteria.where("userId").is(userId)), UserLike.class);

        //- 粉丝: 查询别人喜欢你的用户 (  从`user_like`表中根据`likeUserId`查询所有喜欢我的用户数量 )
        long fanCount = mongoTemplate.count(Query.query(Criteria.where("likeUserId").is(userId)), UserLike.class);
        return new UserLikeCountVo(eachCount,loveCount,fanCount);
    }

    @Override
    public PageBeanVo findEveryDetailByPage(int pageNum, int pageSize, int type, Long userId) {
        //0.计算开始索引
        int startIndex = (pageNum - 1) * pageSize;

        //1.声明各种变量
        Query query = null;
        List<UserLikeVo> userLikeVoList = new ArrayList<>();
        long count = 0;
        List<UserLike> userLikes = null;


        switch (type){
            case 1:
                //若1,查询好友列表
                query = new Query(
                        Criteria.where("userId").is(userId)
                ).skip(startIndex).limit(pageSize);

                List<Friend> friends = mongoTemplate.find(query, Friend.class);

                //遍历集合,重新封装UserLikeVo
                if (CollUtil.isNotEmpty(friends)) {
                    for (Friend friend : friends) {
                        //封装成UserLikeVo
                        UserLikeVo userLikeVo = new UserLikeVo();
                        userLikeVo.setId(friend.getFriendId());//好友id
                        userLikeVo.setMatchRate(findScore(userId,friend.getFriendId()));//缘分值

                        //放入voList
                        userLikeVoList.add(userLikeVo);
                    }
                }

                count = mongoTemplate.count(query, Friend.class);
                return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
            case 2:
                 //若2,查询我喜欢的列表
                query = new Query(
                        Criteria.where("userId").is(userId)
                ).skip(startIndex).limit(pageSize);

                userLikes = mongoTemplate.find(query, UserLike.class);

                //遍历集合,重新封装UserLikeVo
                if (CollUtil.isNotEmpty(userLikes)) {
                    for (UserLike userLike : userLikes) {
                        //封装UserLikeVo
                        UserLikeVo userLikeVo = new UserLikeVo();

                        userLikeVo.setId(userLike.getLikeUserId());//喜欢的人的id
                        userLikeVo.setMatchRate(findScore(userId,userLike.getLikeUserId()));//缘分值

                        //放入voList中
                        userLikeVoList.add(userLikeVo);
                    }
                }

                //查询中记录数
                count = mongoTemplate.count(query, UserLike.class);
                return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
            case 3:
                //若3,查询喜欢我的列表
                query = new Query(
                        Criteria.where("likeUserId").is(userId)
                ).skip(startIndex).limit(pageSize);

                userLikes = mongoTemplate.find(query, UserLike.class);

                //遍历集合,重新封装UserLikeVo
                if (CollUtil.isNotEmpty(userLikes)) {
                    for (UserLike userLike : userLikes) {
                        //封装UserLikeVo
                        UserLikeVo userLikeVo = new UserLikeVo();

                        userLikeVo.setId(userLike.getUserId());//喜欢我的人的id
                        userLikeVo.setMatchRate(findScore(userId,userLike.getUserId()));//缘分值

                        //放入voList中
                        userLikeVoList.add(userLikeVo);
                    }
                }

                //查询总记录数
                count = mongoTemplate.count(query, UserLike.class);
                return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
            case 4:
                //若4,查询访客列表
                query = new Query(
                        Criteria.where("userId").is(userId)
                ).skip(startIndex).limit(pageSize).with(Sort.by(Sort.Order.desc("date")));

                List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);

                //遍历集合,重新封装UserLikeVo
                if (CollUtil.isNotEmpty(visitors)) {
                    for (Visitor visitor : visitors) {
                        //封装UserLikeVo
                        UserLikeVo userLikeVo = new UserLikeVo();

                        userLikeVo.setId(visitor.getVisitorUserId());//访客id
                        userLikeVo.setMatchRate(findScore(userId,visitor.getVisitorUserId()));//缘分值

                        //放入voList中
                        userLikeVoList.add(userLikeVo);
                    }
                }

                //查询总记录数
                count = mongoTemplate.count(query, UserLike.class);
                return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
        }

        return null;
    }

    //查询缘分值
    private Integer findScore(Long userId, Long friendId) {
        RecommendUser recommendUser = mongoTemplate.findOne(Query.query(Criteria.where("toUserId").is(userId).and("userId").is(friendId)), RecommendUser.class);

        //若没有找到,设置一个默认值
        if (recommendUser == null) {
            return RandomUtil.randomInt(60,99);
        }
        return recommendUser.getScore().intValue();
    }
}
